<template>
  <div class="container" v-loading="loading">
    <el-divider content-position="left"><span class="title-left-color">收货信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="收货人姓名:">{{ form.user_name }}</el-descriptions-item>
        <el-descriptions-item label="手机号:">{{ form.mobile }}</el-descriptions-item>
        <el-descriptions-item label="联系地址:">{{ form.address }}</el-descriptions-item>
        <el-descriptions-item label="配送方式:">{{ form.deliveryName }}</el-descriptions-item>
        <el-descriptions-item label="物流公司:" v-if="form.delivery_type === 'expressDelivery'">{{ form.delivery_type }}</el-descriptions-item>
        <el-descriptions-item label="物流单号:" v-if="form.delivery_type === 'expressDelivery'">{{ form.express_no }}</el-descriptions-item>
        <el-descriptions-item label="业务员姓名:" v-if="form.delivery_type === 'salesmanDistribution'">{{ form.staff_info!.staff_name }}</el-descriptions-item>
        <el-descriptions-item label="业务员联系方式:" v-if="form.delivery_type === 'salesmanDistribution'">{{ form.staff_info!.staff_mobile }}</el-descriptions-item>
        <el-descriptions-item label="用户备注:">{{ form.buyer_remark }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div style="margin: 0 70px" v-if="form.delivery_type === 'expressDelivery'">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="收货信息:">{{ form.user_name }} {{ form.mobile }} {{ form.address }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left"><span class="title-left-color">订单信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="订单编号:">{{ form.order_no }}</el-descriptions-item>
        <el-descriptions-item label="订单状态:">{{ form.statusName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间:">{{ form.create_time }}</el-descriptions-item>
        <el-descriptions-item label="支付时间:">{{ form.pay_time }}</el-descriptions-item>
        <el-descriptions-item label="发货时间:">{{ form.delivery_time }}</el-descriptions-item>
        <el-descriptions-item label="收货时间:">{{ form.receipt_time }}</el-descriptions-item>
        <el-descriptions-item label="申请退款时间:">{{ form.apply_refund_time }}</el-descriptions-item>
        <el-descriptions-item label="退款时间:">{{ form.refund_time }}</el-descriptions-item>
        <el-descriptions-item label="退款驳回时间:">{{ form.reject_time }}</el-descriptions-item>
        <el-descriptions-item label="取消时间:">{{ form.cancel_time }}</el-descriptions-item>
        <el-descriptions-item label="支付方式:">{{ form.payName }}</el-descriptions-item>
        <el-descriptions-item label="商家备注:">{{ form.seller_remark }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left"><span class="title-left-color">商品信息</span></el-divider>
    <el-table :data="form.goods" border class="table" show-summary :summary-method="getSummaries" :reserve-selection="true">
      <el-table-column type="index" width="55" align="center"> </el-table-column>
      <el-table-column prop="goods_images" label="图片" width="150" align="center">
        <template #default="scope">
          <el-image style="width: 60px; height: 60px" :src="scope.row.goodsImgList[0]" :preview-src-list="scope.row.goodsImgList"> </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名称" align="center" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="sku_name" label="规格" align="center">
        <template #default="scope">
          {{ [null, ""].includes(scope.row.sku_name) ? "--" : scope.row.sku_name }}
        </template>
      </el-table-column>
      <el-table-column prop="goods_price" label="单价" align="center" sortable> </el-table-column>
      <el-table-column prop="num" label="数量" align="center" sortable> </el-table-column>
      <el-table-column prop="total_price" label="总价" align="center" sortable> </el-table-column>
    </el-table>
    <el-divider content-position="left"><span class="title-left-color">费用信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="商品总价:">{{ form.goods_price }}元</el-descriptions-item>
        <el-descriptions-item label="红包抵扣:">{{ form.red_packet_price }}元</el-descriptions-item>
        <el-descriptions-item label="运费:">{{ form.deliver_price }}元</el-descriptions-item>
        <el-descriptions-item label="优惠金额:">
          {{ form.reduce_price }}
        </el-descriptions-item>
        <el-descriptions-item label="实付金额:">{{ form.pay_price }}元</el-descriptions-item>
        <el-descriptions-item label="实付金额计算公式:">商品总价－红包抵扣－优惠金额＋运费</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left"><span class="title-left-color">操作记录</span></el-divider>
    <el-table :data="form.logs" border class="table" :reserve-selection="true">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="type" label="操作平台" align="center"> </el-table-column>
      <el-table-column prop="user_id" label="用户id" align="center"> </el-table-column>
      <el-table-column prop="user_name" label="用户名" align="center"> </el-table-column>
      <el-table-column prop="desc" label="描述" align="center"> </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center"> </el-table-column>
    </el-table>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-permission="'getOrderPrint'" v-if="['toBeDelivered', 'toBeReceived', 'completed'].includes(form.status)" @click="handleToPrint">去打印</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IMallOrderDetailVO, SummaryMethodProps } from "@/types/redPacketMallManage/mallOrder";
import { getMallOrderByIdInfo } from "@/utils/api/mallOrder";
import { IMG_URL } from "@/utils/config";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();

const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleToPrint: [id: number];
}>();

const isDisabledbtn = ref(false);
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IMallOrderDetailVO>({
  id: 0,
  order_no: "",
  status: "",
  statusName: "",
  express_id: "",
  express_no: "",
  express_name: null,
  user_name: "",
  mobile: "",
  address: "",
  create_time: "",
  pay_time: "",
  delivery_time: "",
  cancel_time: "",
  refund_time: "",
  reject_time: "",
  receipt_time: "",
  apply_refund_time: "",
  buyer_remark: "",
  seller_remark: "",
  goods_price: 0,
  total_price: 0,
  deliver_price: 0,
  red_packet_price: 0,
  gold_coin_price: 0,
  reduce_price: 0,
  pay_price: 0,
  payName: null,
  delivery_type: "",
  deliveryName: "",
  staff_info: {
    staff_name: "",
    staff_mobile: ""
  },
  goods: [],
  logs: []
});
onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetMallOrderByIdInfo(id);
    }
  }
);

/* 统计数量，价格 */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: (string | VNode)[] = [];
  columns.forEach((column, index) => {
    // if (index === 0) {
    //   sums[index] = h("div", { style: { textDecoration: "underline" } }, ["合计"]);
    //   return;
    // }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => Number.isNaN(value))) {
      if (column.property === "goods_image" || column.property === "goods_price" || column.property === "sku_name" || column.property === "goods_name") {
        sums[index] = "";
        return;
      }
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          // return prev + curr;
          return Number((prev + curr).toFixed(2));
        } else {
          return prev;
        }
      }, 0)}`;
      if (column.property === "num") {
        sums[index] += " 件";
        return;
      }
      if (column.property === "total_price") {
        sums[index] += " 元";
        return;
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;
  form.id = 0;
  form.reduce_price = 0;
  form.delivery_type = "";
  form.order_no = "";
  form.status = "";
  form.statusName = "";
  form.express_id = "";
  form.express_no = "";
  form.user_name = "";
  form.mobile = "";
  form.address = "";
  form.create_time = "";
  form.pay_time = "";
  form.delivery_time = "";
  form.cancel_time = "";
  form.refund_time = "";
  form.reject_time = "";
  form.receipt_time = "";
  form.apply_refund_time = "";
  form.buyer_remark = "";
  form.seller_remark = "";
  form.goods_price = 0;
  form.total_price = 0;
  form.deliver_price = 0;
  form.red_packet_price = 0;
  form.gold_coin_price = 0;
  form.reduce_price = 0;
  form.pay_price = 0;
  form.logs = [];
  form.goods = [];
  form.staff_info!.staff_mobile = "";
  form.staff_info!.staff_name = "";
}
/* 获取订单详情数据 */
function handleGetMallOrderByIdInfo(id: number) {
  toggleState(true);
  getMallOrderByIdInfo<IMallOrderDetailVO, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.reduce_price = res.result.reduce_price;
      form.delivery_type = res.result.delivery_type;

      form.order_no = res.result.order_no;
      form.status = res.result.status;
      form.statusName = res.result.statusName;

      form.express_id = res.result.express_id === 0 ? "" : res.result.express_id;

      form.express_name = res.result.express_name;
      form.express_no = res.result.express_no;

      if (res.result.staff_info) {
        form.staff_info!.staff_name = res.result.staff_info.staff_name;
        form.staff_info!.staff_mobile = res.result.staff_info.staff_mobile;
      }

      form.user_name = res.result.user_name;
      form.mobile = res.result.mobile;
      form.address = res.result.address;
      form.create_time = res.result.create_time;
      form.pay_time = res.result.pay_time;
      form.delivery_time = res.result.delivery_time;
      form.cancel_time = res.result.cancel_time;
      form.apply_refund_time = res.result.apply_refund_time;
      form.refund_time = res.result.refund_time;
      form.reject_time = res.result.reject_time;
      form.receipt_time = res.result.receipt_time;
      form.buyer_remark = res.result.buyer_remark;
      form.seller_remark = res.result.seller_remark;
      form.goods_price = res.result.goods_price;
      form.total_price = res.result.total_price;
      form.deliver_price = res.result.deliver_price;
      form.red_packet_price = res.result.red_packet_price;
      form.gold_coin_price = res.result.gold_coin_price;
      form.pay_price = res.result.pay_price;
      /* 操作日志 */
      form.logs = res.result.logs;
      res.result.goods.forEach(item => {
        item.goodsImgList = item.goods_image.split(",").map(_item => IMG_URL + _item);
      });
      form.goods = res.result.goods;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

/* 去打印 */
function handleToPrint() {
  emit("handleToPrint", form.id);
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

.img-item {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
</style>
